package com.util;


import java.awt.Desktop;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;


public class IOUtil
{
	public  String path="container.dat";

	public IOUtil() {
		super();
	}
	public  void write(Object container)
	{
		write(container, path);
	}
	public  void write(Object container,String path)
	{
		if (container==null)
		{
			return;
		}
		ObjectOutputStream ooStream=null;
		try {
			ooStream=new ObjectOutputStream(new FileOutputStream(path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			ooStream.writeObject(container);
			ooStream.flush();
			ooStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public  void write(Object container,File f)
	{
		if (container==null)
		{
			return;
		}
		ObjectOutputStream ooStream=null;
		try {
			ooStream=new ObjectOutputStream(new FileOutputStream(f));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			ooStream.writeObject(container);
			ooStream.flush();
			ooStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public  void write(String content,String path,String charset)
	{
		write(content, path, charset, true);
	}
	public  void write(String content,String path,String charset,boolean append)
	{
	
		File logFile=new File(path);
		if (logFile.exists()==false) {
			try {
				logFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//write log
		OutputStreamWriter writer=null;
		FileOutputStream fileOutputStream=null;
		try {
			fileOutputStream=new FileOutputStream(logFile, append);
			writer=new OutputStreamWriter(fileOutputStream,charset);
		} catch (FileNotFoundException e) {
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			writer.write(content);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public  Object read()
	{
		return read(path);
	}
	public  Object read(String path)
	{
		if (path==null)
		{
			return null;
		}
		if (new File(path).exists()==false)
		{
			return null;
		}
		ObjectInputStream oiStream=null;
		Object container=null;
		try {
			oiStream=new ObjectInputStream(new FileInputStream(path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			container=oiStream.readObject();
			oiStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return container;
	}
	public  Object read(File f)
	{
		if (path==null)
		{
			return null;
		}
		System.out.println(f.getAbsolutePath());
		if (f.exists()==false)
		{
			return null;
		}
		ObjectInputStream oiStream=null;
		Object container=null;
		try {
			oiStream=new ObjectInputStream(new FileInputStream(f));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();  
		}
		
		try {
			container=oiStream.readObject();
			oiStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return container;
	}
	public  String read(String path,String charset,String anthorChar)
	{
		StringBuffer buffer = new StringBuffer("");
        try 
        {
            java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(new FileInputStream(path),charset));
            String line = null;
            while ((line = reader.readLine()) != null)
            {
            	buffer.append(line+anthorChar);
            }
            reader.close();
        }
        catch (Exception e) 
        {
            e.printStackTrace(); 
        }
        
        return buffer.toString();
	}
	public   String read(File file ,String charset,String anthorChar)
	{
		StringBuffer buffer = new StringBuffer("");
        try 
        {
            java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(new FileInputStream(file),charset));
            String line = null;
            while ((line = reader.readLine()) != null)
            {
            	buffer.append(line+anthorChar);
            }
            reader.close();
        }
        catch (Exception e) 
        {
            e.printStackTrace(); 
        }
        
        return buffer.toString();
	}
	 public   String http(String urlStr,String charactor)
	   {
		// System.out.println("IOUtil readUrlContent url= "+urlStr);
			if(charactor==null){charactor="utf-8";}
	    	StringBuffer document = new StringBuffer("");
	        try 
	        {
	            java.net.URL url = new java.net.URL(urlStr);
	            java.net.URLConnection conn = url.openConnection();
	            java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),charactor));
	            String line = null;
	            while ((line = reader.readLine()) != null)
	            {
	            	document.append(line+"\n");
	            	//System.out.println(line);
	            }
	            reader.close();
	        }
	        catch (Exception e) 
	        {
	            e.printStackTrace(); 
	        }
	        
	        return document.toString();
	    }
	 public  void httpObject(String url,String savePath)
	   {
	    	try {       
	            BufferedInputStream  in = new BufferedInputStream(new URL(url).openStream());
	            File file = new File(savePath);   
	            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
	            byte[] buf = new byte[2048];
	            int length = in.read(buf);
	            while(length != -1) {
	                out.write(buf,0,length);
	                length = in.read(buf);
	            }   
	            in.close();   
	            out.close();   
	        } catch (MalformedURLException e) {   
	            e.printStackTrace();   
	        } catch (IOException e) {   
	            e.printStackTrace();   
	        }
	        System.out.println("HttpObject finish :"+url+" --> "+savePath);
	    }
	 public  boolean httpEffective(String source,int ms)
	 {  
		 ExecutorService service = Executors.newFixedThreadPool(1);
			TimeoutCall call=new TimeoutCall(source);
			Object obj=null;
				try {
					Future future = service.submit(call);
					obj = future.get(ms, TimeUnit.MILLISECONDS); //set timeout time is 1000 ms
					service.shutdown();
					System.out.println("httpEffective Successfuly and result= " + obj);
				} catch (Exception e) {
					//e.printStackTrace();
					service.shutdown();
					return false;
				} 
		 return Boolean.parseBoolean(obj+"");
	 }
	 public  String httpTimeout(String source,int ms,String charset)
	 {  
		 ExecutorService service = Executors.newFixedThreadPool(1);
			HttpTimeoutCall call=new HttpTimeoutCall(source,charset);
			String obj="";
				try {
					Future future = service.submit(call);
					obj = future.get(ms, TimeUnit.MILLISECONDS)+""; //set timeout time is 1000 ms
					service.shutdown();
					System.out.println("httpTimeout Successfuly and result= " + obj);
				} catch (Exception e) {
					//e.printStackTrace();
					service.shutdown();
					//return false;
				} 
		 return obj;
	 }
	 public  void open(String url)
	 {
		 try {
			java.net.URI uri=new java.net.URI(url); 
			 java.awt.Desktop.getDesktop().browse(uri);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	 }
	 public  void openFile(String path)
	 {
		openFile(new File(path));
	 }
	 public  void openFile(File file)
	 {
		 try {
			Desktop.getDesktop().open(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	 }
	 public  Map<String,String> toMap(String strs,String seperator1,String seperator2)
	 {
		 Map<String,String> map=new HashMap<String, String>(); 
		 String[] keys=strs.split(seperator1);
		 String key="";
		 for (int i = 0; i < keys.length; i++) 
		 {
			 key=keys[i];
			 if ((key!=null)&&(key.trim().length()>2)&&(key.split(seperator2).length==2))
			 {
				 map.put(key.split(seperator2)[0].trim(), key.split(seperator2)[1]);
			 }
		}
		 return map;
		 
	 }
	 public List<String> toList(String strs,String sep)
	 {
		 List<String> list=new ArrayList<String>();
		 String[] keys=strs.split(sep);
		 String key="";
		 for (int i = 0; i < keys.length; i++) 
		 {
			 key=keys[i];
			 if ((key!=null)&&(key.trim().length()>0))
			 {
				list.add(key);
			 }
		}
		 
		 return list;
	 }
	 public  String isUTF8(String path)
		{
			File file = new File(path);
	        InputStream in=null;;
			try {
				in = new java.io.FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
	        byte[] b = new byte[3];
	        try 
	        {
				in.read(b);
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	        if (b[0] == -17 && b[1] == -69 && b[2] == -65)
	        {
	             return "utf-8";//is utf-8
	        }
	        else
	        {
	     		return "gbk";// is gbk or other
	        }
		}
	public static void main(String[] args) {
		String url="http://10.1.1.1/certsrv/";
		IOUtil ioUtil=new IOUtil();
		String htmlString=ioUtil.http(url, "utf-8");
		System.out.println(htmlString);
	}
}
class TimeoutCall implements Callable<Boolean>
{
	private String source="";
	public TimeoutCall() {
	}
	public TimeoutCall(String source) {
		super();
		this.source = source;
	}
	public Boolean call() throws Exception 
	{
	       try {  
	           URL url = new URL(source);
	           URLConnection uc = url.openConnection();
	         //  uc.setConnectTimeout(1);//
	           InputStream in = uc.getInputStream();
	          // if (source.equalsIgnoreCase(uc.getURL().toString())) return false;  
	           in.close();
	           return true;  
	       } catch (Exception e) 
	       {  
	    	   //e.printStackTrace();
	             return false;  
	       }  
	}
	
}
class HttpTimeoutCall implements Callable<String>
{
	private String urlStr="";
	private String charset="utf-8";
	
	public HttpTimeoutCall(String url, String charset) {
		super();
		this.urlStr = url;
		this.charset = charset;
	}

	public String call() throws Exception 
	{
    	StringBuffer document = new StringBuffer("");
        try 
        {
            java.net.URL url = new java.net.URL(urlStr);
            java.net.URLConnection conn = url.openConnection();
            java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),charset));
            String line = null;
            while ((line = reader.readLine()) != null)
            {
            	document.append(line);
            	//System.out.println(line);
            }
            reader.close();
        }
        catch (Exception e) 
        {
            //e.printStackTrace(); 
        }
        
        return document.toString();
	}
	
}
